package com.iot.common.security.service;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.iot.common.core.constant.SecurityConstants;
import com.iot.common.core.util.R;
import com.iot.common.security.domain.SimpleUser;
import com.iot.manage.api.domain.SysMenu;
import com.iot.manage.api.domain.SysRole;
import com.iot.manage.api.domain.SysUser;
import com.iot.manage.api.feign.RemoteUserService;

@RequiredArgsConstructor
@Service("securityUserDetailsService")
public class SecurityUserDetailsService implements UserDetailsService {
	private final RemoteUserService remoteUserService;

	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		R<SysUser> r = remoteUserService.info(username);
		if (r == null || r.getData() == null) {
			throw new UsernameNotFoundException(String.format("【%s】不存在.", username));
		}
		SysUser user = r.getData();
		Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
		List<SysRole> roles = user.getRoles();
		if (roles != null && roles.size() > 0) {
			Set<String> dbAuthsSet = new HashSet<String>();
			// 获取角色
			for (SysRole role : roles) {
				dbAuthsSet.add(SecurityConstants.ROLE + role.getCode());
			}
			for (SysMenu menu : user.getPermissions()) {
				if(!ObjectUtils.isEmpty(menu.getCode())) {
					authorities.add(new SimpleGrantedAuthority(menu.getCode()));
				}
			}
		}
		return new SimpleUser(user.getId(), user.getUsername(), user.getPassword(), user.getName(), authorities);
	}

}
